<?php
if (!defined('ABSPATH')) { exit; }

// 可选：读取一些概览数据
global $wpdb;
$indexing_table = $wpdb->prefix . 'spider_indexing_status';
$total_rows = $wpdb->get_var("SELECT COUNT(*) FROM $indexing_table");
?>

<div class="wrap">
    <h1>收录分析</h1>
    <p class="description">根据蜘蛛访问与推送记录，对URL的收录状态进行基础分析与管理。</p>
    <?php if (!function_exists('wp_spider_is_premium') || !wp_spider_is_premium()): ?>
        <div class="notice notice-warning"><p>部分功能为高级功能，请在“许可证”或“PRO版本”页面激活后使用。</p></div>
    <?php endif; ?>

    <div class="card">
        <h2>手动检测</h2>
        <form id="spider-indexing-check-form" onsubmit="return false;">
            <input type="url" name="url" id="spider-indexing-url" class="regular-text" placeholder="输入要检测的URL，例如：https://example.com/post-1" />
            <select id="spider-indexing-engine">
                <option value="baidu">百度</option>
                <option value="bing">必应</option>
                <option value="google">谷歌</option>
                <option value="360">360</option>
                <option value="sogou">搜狗</option>
            </select>
            <button class="button button-primary" id="spider-indexing-check-btn">检测</button>
        </form>
        <div id="spider-indexing-check-result" style="margin-top:10px;"></div>
    </div>

    <div class="card">
        <h2>批量检测（高级功能）</h2>
        <p class="description">升级订阅后可一次性检测文章/页面的收录状态。</p>
        <div>
            <select id="spider-indexing-batch-engine">
                <option value="baidu">百度</option>
                <option value="bing">必应</option>
                <option value="google">谷歌</option>
                <option value="360">360</option>
                <option value="sogou">搜狗</option>
            </select>
            <input type="number" id="spider-indexing-batch-count" value="100" min="1" max="2000" step="1" style="width:100px;margin-left:8px;" placeholder="检测数量" />
            <button class="button" id="spider-indexing-batch-btn" <?php echo (function_exists('wp_spider_is_premium') && wp_spider_is_premium()) ? '' : 'disabled'; ?>>开始批量检测</button>
            <button class="button" id="spider-indexing-batch-stop-btn" <?php echo (function_exists('wp_spider_is_premium') && wp_spider_is_premium()) ? '' : 'disabled'; ?> style="margin-left:6px;">结束批量检测</button>
            <span id="spider-indexing-batch-note" style="margin-left:8px;color:#666;"><?php echo (function_exists('wp_spider_is_premium') && wp_spider_is_premium()) ? '已激活，可使用' : '需要高级订阅'; ?></span>
        </div>
        <div id="spider-indexing-batch-progress" style="margin-top:10px;"></div>
    </div>

    <div class="card">
        <h2>收录记录（共 <span id="spider-indexing-total"><?php echo intval($total_rows); ?></span> 条）</h2>
        <div style="margin-bottom:10px;">
            <label>搜索引擎：</label>
            <select id="spider-indexing-filter-engine">
                <option value="all">全部</option>
                <option value="baidu">百度</option>
                <option value="bing">必应</option>
                <option value="google">谷歌</option>
                <option value="360">360</option>
                <option value="sogou">搜狗</option>
            </select>
        </div>
        <table class="widefat fixed striped">
            <thead>
                <tr>
                    <th>URL</th>
                    <th>引擎</th>
                    <th>状态</th>
                    <th>上次蜘蛛访问</th>
                    <th>HTTP</th>
                    <th>上次检测</th>
                </tr>
            </thead>
            <tbody id="spider-indexing-table-body">
                <tr><td colspan="6">加载中...</td></tr>
            </tbody>
        </table>
        <div id="spider-indexing-pagination" style="margin-top:10px;"></div>
    </div>
</div>

<script>
(function($){
    // 统一令牌失效/授权提示（仅用于批量检测）
    function isTokenInvalidResponse(resp){
        var msg = resp && resp.data && (resp.data.message || resp.data.error || '');
        return resp && resp.success === false && typeof msg === 'string' && msg.indexOf('访问令牌无效或已过期') !== -1;
    }
    function ensureTokenBanner(upgradeUrl){
        if ($('.token-invalid-banner').length) return;
        var url = upgradeUrl || (window.wpSpiderMonitor ? wpSpiderMonitor.ajax_url.replace('admin-ajax.php','admin.php?page=spider-license') : '#');
        var html = ''+
            '<div class="token-invalid-banner premium-notice" style="margin:12px 0;">' +
                '<div class="premium-restriction">' +
                    '<span class="premium-icon">🔒</span>' +
                    '<span class="premium-text">访问令牌无效或已过期</span>' +
                    '<a href="'+ url +'" class="premium-link">立即激活</a>' +
                '</div>' +
            '</div>';
        $('.wrap').first().prepend(html);
    }
    function showBatchAreaPremium(progressSelector, upgradeUrl){
        var url = upgradeUrl || (window.wpSpiderMonitor ? wpSpiderMonitor.ajax_url.replace('admin-ajax.php','admin.php?page=spider-license') : '#');
        var html = ''+
            '<div class="premium-restriction">' +
                '<span class="premium-icon">🔒</span>' +
                '<span class="premium-text">访问令牌无效或已过期</span>' +
                '<a href="'+ url +'" class="premium-link">立即激活</a>' +
            '</div>';
        $(progressSelector).html(html);
    }
    // 批量检测按钮逻辑：仅高级订阅可用
    $('#spider-indexing-batch-btn').on('click', function(){
        if (!(window.wpSpiderMonitor && wpSpiderMonitor.subscription && wpSpiderMonitor.subscription.is_premium)) {
            alert('批量检测为高级功能，请在许可证页面激活订阅');
            return;
        }
        var count = parseInt($('#spider-indexing-batch-count').val(), 10) || 0;
        if (count <= 0) { alert('请输入有效的检测数量'); return; }
        if (count > 2000) { alert('单次最多检测2000条'); return; }
        $('#spider-indexing-batch-progress').text('准备中...');
        $.post(ajaxurl, {
            action: 'spider_indexing_batch_check',
            engine: $('#spider-indexing-batch-engine').val(),
            count: count,
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(resp){
            if (resp && resp.success) {
                $('#spider-indexing-batch-progress').html('已启动批量检测任务，后台运行中... <span id="spider-indexing-batch-counter" class="badge badge-success">0</span>');
                startBatchProgressPolling();
            } else if (isTokenInvalidResponse(resp)) {
                ensureTokenBanner(resp && resp.data && resp.data.upgrade_url);
                showBatchAreaPremium('#spider-indexing-batch-progress', resp && resp.data && resp.data.upgrade_url);
            } else {
                $('#spider-indexing-batch-progress').text('批量任务启动失败');
            }
        });
    });

    // 结束批量检测
    $('#spider-indexing-batch-stop-btn').on('click', function(){
        if (!(window.wpSpiderMonitor && wpSpiderMonitor.subscription && wpSpiderMonitor.subscription.is_premium)) {
            alert('批量检测为高级功能，请在许可证页面激活订阅');
            return;
        }
        $('#spider-indexing-batch-progress').text('正在结束批量任务...');
        $.post(ajaxurl, {
            action: 'spider_indexing_batch_stop',
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(resp){
            if (resp && resp.success) {
                $('#spider-indexing-batch-progress').text('批量检测已结束');
                stopBatchProgressPolling();
            } else if (isTokenInvalidResponse(resp)) {
                ensureTokenBanner(resp && resp.data && resp.data.upgrade_url);
                showBatchAreaPremium('#spider-indexing-batch-progress', resp && resp.data && resp.data.upgrade_url);
            } else {
                $('#spider-indexing-batch-progress').text('结束失败，请稍后重试');
            }
        });
    });

    var batchProgressTimer = null;
    function startBatchProgressPolling(){
        stopBatchProgressPolling();
        function poll(){
            $.post(ajaxurl, {
                action: 'spider_indexing_batch_progress',
                nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
            }, function(resp){
                if (resp && resp.success) {
                    if (!resp.data || resp.data.running === false) {
                        stopBatchProgressPolling();
                        return;
                    }
                    var processed = resp.data.processed || 0;
                    var limit = resp.data.limit || 0;
                    $('#spider-indexing-batch-counter').text(processed + (limit>0? (' / ' + limit) : ''));
                }
            }).always(function(){
                batchProgressTimer = setTimeout(poll, 3000);
            });
        }
        poll();
    }
    function stopBatchProgressPolling(){
        if (batchProgressTimer) { clearTimeout(batchProgressTimer); batchProgressTimer = null; }
    }

    function loadIndexingList(engine, page){
        $('#spider-indexing-table-body').html('<tr><td colspan="6">加载中...</td></tr>');
        $.post(ajaxurl, {
            action: 'spider_get_indexing_list',
            engine: engine,
            page: page || 1,
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(resp){
            if(!resp || !resp.success){
                $('#spider-indexing-table-body').html('<tr><td colspan="6">加载失败</td></tr>');
                return;
            }
            var rows = resp.data.rows || [];
            var total = parseInt(resp.data.total || 0, 10);
            $('#spider-indexing-total').text(total);
            if(rows.length === 0){
                $('#spider-indexing-table-body').html('<tr><td colspan="6">暂无数据</td></tr>');
            } else {
                var html = '';
                rows.forEach(function(r){
                    var twoState = (r.status === 'indexed' || r.status === 'indexed_probable') ? '已收录' : '未收录';
                    html += '<tr>'+
                        '<td><a href="'+ (r.url || '#') +'" target="_blank">'+ (r.url || '') +'</a></td>'+
                        '<td>'+ (r.engine_type || '') +'</td>'+
                        '<td>'+ twoState +'</td>'+
                        '<td>'+ (r.last_spider_visit || '-') +'</td>'+
                        '<td>'+ (r.http_status || '-') +'</td>'+
                        '<td>'+ (r.last_checked || '-') +'</td>'+
                    '</tr>';
                });
                $('#spider-indexing-table-body').html(html);
            }
            var pages = resp.data.pages || 1, cur = resp.data.current_page || 1;
            var phtml = '';
            if(pages > 1){
                for(var i=1;i<=pages;i++){
                    if(i === cur){ phtml += '<span style="margin-right:6px;font-weight:bold;">'+i+'</span>'; }
                    else { phtml += '<a href="#" class="spider-indexing-page" data-page="'+i+'" style="margin-right:6px;">'+i+'</a>'; }
                }
            }
            $('#spider-indexing-pagination').html(phtml);
        });
    }

    $('#spider-indexing-filter-engine').on('change', function(){
        loadIndexingList($(this).val(), 1);
    });

    $(document).on('click', '.spider-indexing-page', function(e){
        e.preventDefault();
        var page = parseInt($(this).data('page'), 10) || 1;
        loadIndexingList($('#spider-indexing-filter-engine').val(), page);
    });

    $('#spider-indexing-check-btn').on('click', function(){
        var url = $('#spider-indexing-url').val();
        var engine = $('#spider-indexing-engine').val();
        if(!url){
            alert('请输入URL');
            return;
        }
        $('#spider-indexing-check-result').html('检测中...');
        $.post(ajaxurl, {
            action: 'spider_check_indexing_status',
            url: url,
            engine: engine,
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(resp){
            if(!resp || !resp.success){
                $('#spider-indexing-check-result').html('检测失败');
                return;
            }
            var d = resp.data || {};
            var twoState = (d.status === 'indexed' || d.status === 'indexed_probable') ? '已收录' : '未收录';
            $('#spider-indexing-check-result').html('状态：' + twoState);
            // 重新加载列表，便于看到最新记录
            loadIndexingList($('#spider-indexing-filter-engine').val(), 1);
        });
    });

    // 初始加载
    loadIndexingList($('#spider-indexing-filter-engine').val(), 1);
})(jQuery);
</script>


